package com.wry.wry_test.feign.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Target;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * @Author: wangrongyi
 * @Date: 2024/7/15 13:37
 * @Description:
 */
@Slf4j
public class ThirdServiceInterceptor implements RequestInterceptor {

    @Resource
    private LoadBalanceService loadBalanceService;

    @Override
    public void apply(RequestTemplate requestTemplate) {

        Target.HardCodedTarget<?> target = (Target.HardCodedTarget<?>) requestTemplate.feignTarget();

        // 反射设置target属性
        String addr = loadBalanceService.getServerAddress();

        try {
            log.info("请求地址：{}", addr);
            Field field = Target.HardCodedTarget.class.getDeclaredField("url");
            field.setAccessible(true);
            field.set(target, addr);

        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("设置url失败", e);
        }
    }
}
